package com.ben.xinyue.seckill.service;

import com.ben.xinyue.seckill.controller.MiaoshaController;
import com.ben.xinyue.seckill.domain.entity.MiaoshaOrder;
import com.ben.xinyue.seckill.domain.entity.MiaoshaUser;
import com.ben.xinyue.seckill.domain.entity.OrderInfo;
import com.ben.xinyue.seckill.domain.vo.GoodsVo;
import com.ben.xinyue.seckill.util.MD5Util;
import lombok.RequiredArgsConstructor;
import org.redisson.api.RBucket;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.util.List;
import java.util.Objects;
import java.util.Random;
import java.util.UUID;

@Service
@RequiredArgsConstructor(onConstructor = @__(@Autowired))
public class MiaoshaOrderService  {

    private final MiaoshaGoodsService miaoshaGoodsService;
    private final OrderInfoService orderInfoService;
    private final RedissonClient redissonClient;

    /**
     * 根据用户ID和商品ID 查询具体的订单
     * @param userId 用户ID
     * @param goodsId 商品ID
     * @return 结果
     */
    public MiaoshaOrder queryOrderByUserIdAndGoodsId(Long userId, Long goodsId) {
        MiaoshaOrder miaoshaOrder = (MiaoshaOrder) redissonClient.getBucket("seckill-uid-gid"+userId+goodsId).get();
        return miaoshaOrder;
    }

    /**
     * 秒杀
     * @param user 用户
     * @param goodsVo 商品
     * @return 结果
     */
    @Transactional(rollbackFor = Exception.class)
    public OrderInfo miaosha(MiaoshaUser user, GoodsVo goodsVo) {
        boolean success = miaoshaGoodsService.reduceStock(goodsVo);
        if(success){
            return  orderInfoService.createOrder(user, goodsVo);
        }
        redissonClient.getBucket("miaoshaover"+goodsVo.getId()).set(true);
        return null;
    }


    public BufferedImage createVerifyCode(MiaoshaUser user, long goodsId) {
        if(user == null || goodsId <=0) {
            return null;
        }
        int width = 80;
        int height = 32;
        BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
        Graphics g = image.getGraphics();
        g.setColor(new Color(0xDCDCDC));
        g.fillRect(0, 0, width, height);
        g.setColor(Color.black);
        g.drawRect(0, 0, width - 1, height - 1);
        Random rdm = new Random();
        for (int i = 0; i < 50; i++) {
            int x = rdm.nextInt(width);
            int y = rdm.nextInt(height);
            g.drawOval(x, y, 0, 0);
        }
        String verifyCode = generateVerifyCode(rdm);
        g.setColor(new Color(0, 100, 0));
        g.setFont(new Font("Candara", Font.BOLD, 24));
        g.drawString(verifyCode, 8, 24);
        g.dispose();
        int rnd = calc(verifyCode);
        redissonClient.getBucket(user.getId()+","+goodsId+",verifyCode").set(rnd);
        return image;
    }

    private static char[] ops = new char[] {'+', '-', '*'};

    private static int calc(String exp) {
        try {
            ScriptEngineManager manager = new ScriptEngineManager();
            ScriptEngine engine = manager.getEngineByName("JavaScript");
            return (Integer)engine.eval(exp);
        }catch(Exception e) {
            e.printStackTrace();
            return 0;
        }
    }


    private String generateVerifyCode(Random rdm) {
        int num1 = rdm.nextInt(10);
        int num2 = rdm.nextInt(10);
        int num3 = rdm.nextInt(10);
        char op1 = ops[rdm.nextInt(3)];
        char op2 = ops[rdm.nextInt(3)];
        String exp = ""+ num1 + op1 + num2 + op2 + num3;
        return exp;
    }


    public boolean checkVerifyCode(MiaoshaUser miaoshaUser, long goodsId, int verifyCode) {
        if(miaoshaUser == null || goodsId <=0) {
            return false;
        }
        RBucket code = redissonClient.getBucket(miaoshaUser.getId()+","+goodsId+",verifyCode");
        if(code == null || (Integer) code.get() - verifyCode != 0 ) {
            return false;
        }
        redissonClient.getBucket(miaoshaUser.getId()+","+goodsId+",verifyCode").delete();
        return true;
    }

    public String createMiaoshaPath(MiaoshaUser miaoshaUser, long goodsId) {
        if(miaoshaUser == null || goodsId <=0) {
            return null;
        }
        String str = MD5Util.md5(UUID.randomUUID()+"123456");
        redissonClient.getBucket("miaoshapath"+miaoshaUser.getId() + "_"+ goodsId).set(str);
        return str;
    }

    public long getMiaoshaResult(Long userId, long goodsId) {
        if(MiaoshaController.isGlobalActivityOver()){
            return -1;
        }
        MiaoshaOrder order = orderInfoService.getMiaoshaOrderByUserIdGoodsId(userId, goodsId);
        if(order != null) {
            return order.getOrderId();
        }else {
            boolean isOver = getGoodsOver(goodsId);
            if(!isOver) {
                return 0;
            }else {
                List<MiaoshaOrder> orders = orderInfoService.getAllMiaoshaOrdersByGoodsId(goodsId);
                if(orders == null || orders.size() < MiaoshaController.getGoodsStockOriginal(goodsId)){
                    return 0;
                }else {
                    MiaoshaOrder o = get(orders, userId);
                    if(o != null) {
                        return o.getOrderId();
                    }else {
                        return -1;
                    }
                }
            }
        }

    }

    private MiaoshaOrder get(List<MiaoshaOrder> orders, Long userId) {
        if(orders == null || orders.size() <= 0) {
            return null;
        }
        for(MiaoshaOrder order : orders) {
            if(order.getUserId().equals(userId)) {
                return order;
            }
        }
        return null;
    }

    private boolean getGoodsOver(long goodsId) {
        Object obj = redissonClient.getBucket("miaoshaover"+goodsId).get();
        return Objects.nonNull(obj);
    }

    public boolean checkPath(MiaoshaUser miaoshaUser, Long goodsId, String path) {
        String pathOld = (String) redissonClient.getBucket("miaoshapath"+miaoshaUser.getId() + "_"+ goodsId).get();
        return path.equals(pathOld);
    }
}